<?php

/**
 * Versenyekkel kapcsolatos általános segédfüggvények.
 * 
 * @author poli
 */
class TournamentHandler {

	public static function formatDate($str, $formatter = "%Y. %B %d.") {
		$ts = TextUtil::parseTimestampString($str, "%Y-%m-%d %H:%M:%S");
		if ($ts >= 0) {
			return TextUtil::getFormattedTimestampString($ts, $formatter);
		} else {
			return '';
		}
	}

	public static function getTournamentTypesForCombo($types = null) {
		if (is_null($types)) {
			$types = AdminDBHelper::getTournamentTypes(AdminBase::getCurrentEditlang());
		}
		$result = array();
		foreach ($types as $type) {
			$result[$type['id']] = $type['name'];
		}
		return $result;
	}

	public static function getTournamentConfigurationsForCombo() {
		$config = ConstHandler::get('TOURNAMENT_CONFIGURATION');
		$result = array();
		foreach (array_keys($config) as $configKey) {
			$result[$configKey] = $configKey;
		}
		$result = array_merge(array('default' => 'default'), $result);
		return $result;
	}

	public static function getTournamentConfiguration(&$tournament) {
		$config = ConstHandler::get('TOURNAMENT_CONFIGURATION');
		if (! is_null($config) && is_array($config) && 
				isset($config[$tournament['configuration']])) {
			$result = $config[$tournament['configuration']];
		} else {
			$result = $config['default'];
		}
		return $result;
	}

	/**
	 * Visszaadja a megadott versenyhez tartozó regisztrációs űrlap
	 * extra mezőit a konfigurációnak megfelelően.
	 *
	 * @param array $tournament Verseny adatai.
	 * @param array $values Alapértelmezetten erre van kitöltve.
	 */
	public static function getTournamentRegistrationFields($tournament, $values = null) {
		$fieldsTpl = TemplateUtil::loadSharedTemplateFile("tournamentfields.tpl.html");
		TextHandler::insertTextsIntoTemplate($fieldsTpl);
		$tc = TournamentHandler::getTournamentConfiguration($tournament);
		if (isset($values['properties'])) {
			if (! is_array($values['properties'])) {
				$properties = json_decode($values['properties'], true);
			} else {
				$properties = $values['properties'];
			}
			if (is_array($properties)) {
				$values = array_merge($values, $properties);
				unset($values['properties']);
			}
		}
		foreach ($tc as $key => $value) {
			if (TextUtil::startsWith($key, 'field_')) {
				$fieldName = substr($key, strlen('field_'));
				if (! is_null($values)) $fieldValue = $values[$fieldName];
				else $fieldValue = null;
				if (is_array($value)) {
					$options = FormUtil::getComboOptionHTMLTagsFromAssociativeArray($value, $fieldValue, true);
					$fieldsTpl->setVariable('form_'.$fieldName, $options);
				} else if (! $value) {
					$fieldsTpl->replaceBlock($fieldName, '');
				} else {
					// normális érték
					$fieldsTpl->setVariable('form_'.$fieldName, $fieldValue);
				}
				$fieldsTpl->touchBlock($fieldName);
			}
		}
		if (! is_null($values)) {
			$fieldsTpl->setVariable('form_name', $values['name']);
			$fieldsTpl->setVariable('form_email', $values['email']);
		} else {
			$fieldsTpl->setVariable('form_name', '');
			$fieldsTpl->setVariable('form_email', '');
		}
		return $fieldsTpl;
	}

	/**
	 * Visszaadja a POST paraméterek alapján a jelentkezés adatait.
	 *
	 * @param array $tournament Tournament adatai.
	 * @param array $tournamentTypeId Verseny típusa.
	 * @param int $timestamp Jelentkezés ideje.
	 */
	public static function getTournamentRegistrationData($tournament, $tournamentTypeId, $timestamp = null) {
		if (empty($timestamp) || $timestamp <= 0) {
			$timestamp = time();
		}
		$tc = TournamentHandler::getTournamentConfiguration($tournament);
		$properties = array();
		$calculation = false;
		foreach ($tc as $key => $value) {
			if (TextUtil::startsWith($key, 'field_')) {
				$fieldName = substr($key, strlen('field_'));
				if ($value) {
					$postValues = FunctionLibrary::getPostValue($fieldName);
					foreach ($postValues as $index => $postValue) {
						if (! isset($properties[$index])) $properties[$index] = array();
						$properties[$index][$fieldName] = $postValue;
					}
				}
			} else if ($key == 'calculation') {
				$calculation = $value;
			}
		}
		if ($calculation !== false) {
			// meghívja a kalkulációs függvényt, ami módosíthat
			// az értékeken
			foreach ($properties as $index => $propertyValues) {
				$properties[$index] = call_user_func($calculation, $tournament, $tournamentTypeId, $timestamp, $propertyValues);
			}
		}
		return $properties;
	}

	/**
	 * Megadott adatok alapján teljes email-eket generál.
	 *
	 * @param array $names Nevek.
	 * @param array $emails Email címek.
	 * @param array $properties Custom tulajdonságok.
	 * @param int $tournamentType Versenyforma azonosítója.
	 */
	public static function getRecipientsForTournamentRegistrationEmail($names, $emails, $properties, $tournamentType) {
		$recipients = array();
		for ($i = 0; $i < count($names); $i++) {
			if (! empty($names[$i]) && ! empty($emails[$i]) && FunctionLibrary::checkEmailSyntax($emails[$i])) {
				$recipient = new AlertRecipient();
				$recipient->sendHere = $emails[$i];
				$recipient->langcodes = array(TextHandler::getCurrentLangcode());
				if ($properties[$i]['foreigner']) {
					$recipient->langcodes = array('en');
				}
				// tournament type
				$ttype = SiteDBHelper::getTournamentType($tournamentType, $recipient->langcodes[0], true);

				$extraPropertiesBuffer = new StringBuffer();				
				if (isset($properties[$i]['lunch'])) {
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_lunch', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append(' ');
					$extraPropertiesBuffer->append(TextHandler::getText('kbbo_lunch_'.$properties[$i]['lunch'], $recipient->langcodes[0]));
					$extraPropertiesBuffer->append("\n");
				}
				if (isset($properties[$i]['gender'])) {
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_gender', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append(' ');
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_gender_'.$properties[$i]['gender'], $recipient->langcodes[0]));
					$extraPropertiesBuffer->append("\n");
				}
				if (isset($properties[$i]['age'])) {
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_age', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append(' ');
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_age_'.$properties[$i]['age'], $recipient->langcodes[0]));
					$extraPropertiesBuffer->append("\n");
				}
				if (isset($properties[$i]['clubMember'])) {
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_clubMember', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append(' ');
					$extraPropertiesBuffer->append(TextHandler::getText($properties[$i]['clubMember']? 'gen_yes': 'gen_no', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append("\n");
				}
				if (isset($properties[$i]['foreigner'])) {
					$extraPropertiesBuffer->append(TextHandler::getText('comp_entry_foreigner', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append(' ');
					$extraPropertiesBuffer->append(TextHandler::getText($properties[$i]['foreigner']? 'gen_yes': 'gen_no', $recipient->langcodes[0]));
					$extraPropertiesBuffer->append("\n");
				}
				$extraProperties = $extraPropertiesBuffer->toString();
				if (! empty($extraProperties)) $extraProperties = "\n$extraProperties\n";
				$recipient->variables = array(
					'name' => $names[$i],
					'fee' => $properties[$i]['fee'],
					'extraProperties' => $extraProperties,
					'extraPropertiesHtml' => nl2br($extraProperties),
					'compType' => $ttype['name']
				);
				$recipients[] = $recipient;
			}
		}
		return $recipients;
	}

}
